package service

import (
	"errors"
	"github.com/go-admin-team/go-admin-core/sdk/service"
	"gorm.io/gorm"
	"tuowei.com/app/admin/models"
	"tuowei.com/app/admin/service/dto"
	"tuowei.com/common/actions"
	cDto "tuowei.com/common/dto"
	"tuowei.com/pkg/xlog"
)

type SysOfflineCourse struct {
	service.Service
}

// GetAppPage 获取SysOfflineCourse列表
func (e *SysOfflineCourse) GetAppPage(c *dto.SysOfflineCourseGetPageReq, p *actions.DataPermission, list *[]models.SysOfflineCourseList, count *int64) error {
	var err error
	var data models.SysOfflineCourse
	err = e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
		).Order("course_id asc").
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return err
	}
	return nil
}

// GetPage 获取SysOfflineCourse列表
func (e *SysOfflineCourse) GetPage(c *dto.SysOfflineCourseGetPageReq, p *actions.DataPermission, list *[]models.SysOfflineCourseList, count *int64) error {
	var err error
	var data models.SysOfflineCourse
	err = e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
		).Order("course_id desc").
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return err
	}
	return nil
}

// Insert 创建SysOfflineCourse对象
func (e *SysOfflineCourse) Insert(c *dto.SysOfflineCourseInsertReq) error {
	var err error
	var data models.SysOfflineCourse
	var model models.SysCourseGift
	var i int64
	err = e.Orm.Model(&data).Where("name = ?", c.OfflineStep1.Name).Count(&i).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return err
	}
	if i > 0 {
		err := errors.New("课程名称已存在！")
		e.Log.Errorf("db error: %s", err)
		return err
	}

	c.Generate(&data)

	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return err
	}

	if c.OfflineStep2.CourseGift != nil {
		tmp := []models.SysCourseGift{}
		for _, v := range c.OfflineStep2.CourseGift {
			tmp = append(tmp, models.SysCourseGift{
				CourseId:   data.CourseId,
				GiftType:   v.GiftType,
				CourseType: "offline",
				ObjIds:     v.ObjIds,
			})
		}
		err = e.Orm.Model(model).Create(&tmp).Error
		if err != nil {
			xlog.Error(err)
			return err
		}
	}

	return nil
}

func (e *SysOfflineCourse) UpdateStatus(c *dto.SysOfflineCourseUpdateStatusReq) error {
	var err error
	var model = models.SysOfflineCourse{}
	e.Orm.First(&model, c.GetId())
	c.Generate(&model)
	db := e.Orm.Save(&model)
	err = db.Error
	if err != nil {
		e.Log.Errorf("Service UpdateStatus error:%s", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")

	}
	return nil
}

func (e *SysOfflineCourse) Update(c *dto.SysOfflineCourseUpdateReq) error {
	var err error
	var model = models.SysOfflineCourse{}
	e.Orm.First(&model, c.GetId())
	c.Generate(&model)
	db := e.Orm.Save(&model)
	err = db.Error
	if err != nil {
		e.Log.Errorf("Service UpdateStatus error:%s", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")
	}
	if c.OfflineStep2.CourseGift != nil {
		// 以前的逻辑有bug。。。当gfit表里没数据的时候更新没屁用
		// 先删除gift表里的数据
		for _, v := range c.OfflineStep2.CourseGift {
			e.Orm.Where("course_id = ?", c.GetId()).Where("gift_type = ?", v.GiftType).Delete(models.SysCourseGift{})
			// 重新插入
			e.Orm.Model(models.SysCourseGift{}).Create(&models.SysCourseGift{
				CourseId:   c.CourseId,
				GiftType:   v.GiftType,
				ObjIds:     v.ObjIds,
				CourseType: "offline",
			})
		}

	}

	return nil
}

// Remove 删除SysClass
func (e *SysOfflineCourse) Remove(c *dto.SysOfflineCourseById, p *actions.DataPermission) error {
	var err error
	var data models.SysOfflineCourse

	db := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).Delete(&data, c.GetId())
	if err = db.Error; err != nil {
		e.Log.Errorf("Error found in  RemoveSysCourse : %s", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权删除该数据")
	}
	return nil
}

// Get 获取SysCourse对象
func (e *SysOfflineCourse) Get(d *dto.SysOfflineCourseById, p *actions.DataPermission, model *models.SysOfflineCourse) error {
	var data models.SysOfflineCourse
	var err error
	err = e.Orm.Model(&data).Preload("Lecture").
		Scopes(
			actions.Permission(data.TableName(), p),
		).
		First(model, d.GetId()).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("课程不存在")
		xlog.Errorf("db error: %s", err)
		return err
	}
	if err != nil {
		xlog.Errorf("db error: %s", err)
		return err
	}

	return nil
}

func (e *SysOfflineCourse) BindESignTemplate(req dto.BindESignTemplate) error {
	course := new(models.SysOfflineCourse)
	err := e.Orm.Where("course_id = ?", req.CourseId).Find(course).Error
	if err != nil {
		return err
	}
	return e.Orm.Model(course).Where("course_id = ?", req.CourseId).Update("e_template_id", req.Id).Error
}
